package com.bckj.fastboot.paid.biz.infrastructure.sdk.wechatpay;

import cn.hutool.core.util.NumberUtil;
import com.bckj.fastboot.paid.api.constant.RefundWayConstants;
import com.bckj.fastboot.paid.api.exceptions.RefundException;
import com.bckj.fastboot.paid.api.model.RefundRequest;
import com.bckj.fastboot.paid.api.model.RefundResponse;
import com.bckj.fastboot.paid.biz.domain.pay.gateway.RefundGateway;
import com.bckj.fastboot.paid.biz.domain.pay.provider.RefundGatewayProvider;
import com.bckj.fastboot.paid.biz.infrastructure.sdk.PayServiceManager;
import com.wechat.pay.java.service.refund.RefundService;
import com.wechat.pay.java.service.refund.model.AmountReq;
import com.wechat.pay.java.service.refund.model.CreateRequest;
import com.wechat.pay.java.service.refund.model.Refund;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;

@Component
@RequiredArgsConstructor
public class WechatRefundGateway implements RefundGateway {

    private final PayServiceManager payServiceManager;

    @PostConstruct
    public void init() {
        RefundGatewayProvider.register(getRefundWay(), this);
    }

    @Override
    public String getRefundWay() {
        return RefundWayConstants.WECHAT_REFUND;
    }

    @Override
    public RefundResponse refund(RefundRequest request) throws RefundException {
        WechatRefundServiceWrapper payServiceWrapper = (WechatRefundServiceWrapper) payServiceManager.getPayService(request.getAppId(), request.getRefundWay());
        RefundService refundService = (RefundService) payServiceWrapper.getService();
        CreateRequest wechatRequest = toWechatRequest(request);
        try {
            Refund wechatResponse = refundService.create(wechatRequest);
            return toRefundResponse(wechatResponse);
        } catch (Exception e) {
            throw new RefundException("Wechat Refund Error:" + e.getMessage());
        }
    }

    private CreateRequest toWechatRequest(RefundRequest request) {
        CreateRequest createRequest = new CreateRequest();
        createRequest.setOutTradeNo(request.getOutTradeNo());
        createRequest.setOutRefundNo(request.getOutRefundNo());
        createRequest.setReason(request.getReason());
        createRequest.setNotifyUrl(request.getNotifyUrl());
        AmountReq amountReq = new AmountReq();
        amountReq.setRefund(NumberUtil.mul(request.getAmount(), new BigDecimal("100")).longValue());
        amountReq.setCurrency("CNY");
        amountReq.setTotal(0L);
        createRequest.setAmount(amountReq);
        return createRequest;
    }

    private RefundResponse toRefundResponse(Refund wechatResponse) {
        RefundResponse refundResponse = new RefundResponse();
        return refundResponse;
    }

}
